#!/bin/sh
#chkconfig: 2345 79 31
#
# james          Start/Stop the Apache James mail server.
#

RETVAL=0
prog="james"
exec=/u01/app/james-2.3.2/bin/run.sh

# Source function library.
. /etc/rc.d/init.d/functions

[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

start() {
    export JAVA_HOME=$JAVA_HOME
    if [ $UID -ne 0 ] ; then
        echo "User has insufficient privilege."
        exit 4
    fi
    touch /var/lock/subsys/$prog
    PID=`echo | ps -ef | awk '/[j]ames-2.3.2/{print $2}'`
    if [[ -n $PID ]]; then
       echo $prog" is already running"
    fi
    if [[ -z $PID ]]; then
      if [[ -z $JAVA_HOME ]]; then
         echo "JAVA_HOME is not set, please set it in /etc/sysconfig/"$prog
         echo $prog" could not start because JAVA_HOME is not set"
         exit 1
      fi
      echo -n "Starting "$prog": "
      sh /u01/app/james-2.3.2/bin/run.sh > /var/log/james.log 2>&1 &
      SUCCESS=`cat /var/log/james.log | grep FetchMail`
      SECS=1
      while [[ -z $SUCCESS ]] && [[ $SECS -le 30 ]]
      do
         sleep 1
         SUCCESS=`cat /var/log/james.log | grep FetchMail`
         SECS=$(( $SECS+1 ))
      done
      if [[ -n $SUCCESS ]]; then
         echo -e "\t\t\t\t\t   [\e[0;32m  OK  \e[0m]"
      fi
      if [[ -z $SUCCESS ]]; then
        echo -e "\t\t\t\t\t   [\e[0;31m  FAILED  \e[0m]"
      fi
    fi 
}

stop() {
    if [ $UID -ne 0 ] ; then
        echo "User has insufficient privilege."
        exit 4
    fi
    PID=`echo | ps -ef | awk '/[j]ames-2.3.2/{print $2}'`
    if [[ -z $PID ]]; then
       echo $prog" is not running"
    fi
    if [[ -n $PID ]]; then
       echo -n "Stopping "$prog": "
       kill -9 $PID
       sleep 2
       PID=`echo | ps -ef | awk '/[j]ames-2.3.2/{print $2}'`
       if [[ -n $PID ]]; then
          echo -e "\t\t\t\t\t   [\e[0;31m  FAILED  \e[0m]"
       fi
       if [[ -z $PID ]]; then
          echo -e "\t\t\t\t\t   [\e[0;32m  OK  \e[0m]"
          rm -rf /var/lock/subsys/$prog
       fi
    fi
}

restart() {
    stop
    start
}

rh_status() {
    # run checks to determine if the service is running or use generic status
    PID=`echo | ps -ef | awk '/[j]ames-2.3.2/{print $2}'`
    if [[ -n $PID ]]; then
       echo $prog" is running with PID: "$PID
    fi
    if [[ -z $PID ]]; then
      echo $prog "is not running"
    fi
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}


case "$1" in
    start)
        #rh_status_q && exit 0
        $1
        ;;
    stop)
        #rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    status)
        rh_status
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 2
esac
exit $?
